﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// 消息输入
/// </summary>
public class ChatInput : MonoBehaviour
{
    // 输入框
    [SerializeField] private InputField MsgInputField;
    // 发送按钮
    [SerializeField] private Button EnterBtn;

    // 自身识别ID
    public int UID;
    public string ipAndPort;
    public Text ipAndPortText;
    Socket socketClient;
    public ChatBubble chatBubble;
    public RectTransform text;
    public Queue<string> msgQueue = new Queue<string>();

    private void Awake()
    {
        EnterBtn.onClick.AddListener(OnClickEnterBtn);
    }

    private void OnClickEnterBtn()
    {
        if (string.IsNullOrEmpty(MsgInputField.text)) return;

        //ChatEventHub.I.NotifyChatMsg(UID, MsgInputField.text);
        NetManager.Manager.SendAsync(new Msg()
        {
            Command = "SendChatMsg",
            Client = NetManager.Manager.GetInfo(),
            Value = MsgInputField.text
        });
    }
    private void SendAsync(string value)
    {
        byte[] sendBytes = Encoding.UTF8.GetBytes(value);//把字符串转化为byte
        socketClient.BeginSend(sendBytes, 0, sendBytes.Length, 0, SendCallBack, socketClient);
    }

    private void SendCallBack(IAsyncResult ar)
    {
        try
        {
            Socket socket = (Socket)ar.AsyncState;
            int count = socket.EndSend(ar);
            Debug.Log("信息发送成功，长度为：" + count);
        }
        catch (SocketException se)
        {
            Debug.LogError(se.Message);
        }
    }

    private string FormatAddress(Socket socket)
    {
        string clientIP = ((IPEndPoint)socket.LocalEndPoint).Address.ToString();
        string clientPort = ((IPEndPoint)socket.LocalEndPoint).Port.ToString();
        return string.Format("{0}:{1}", clientIP, clientPort);
    }



    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

        if (msgQueue.Count > 0)
        {
            chatBubble.ShowChat(msgQueue.Dequeue());
        }
    }
}
